package com.gxa.finance.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitmqConfig {

    //延迟交换机名称
    public static final String DELAY_EXCHANGE="delay_exchange_name";
    //延时队列名称
    public static final String DELAY_QUEUE="delay_queuea_name";
    //死信交换机名称
    public static final String DEAD_LETTER_EXCHANGE="dead_letter_exchange_name";
    //死信队列名称
    public static final String DEAD_LETTER_QUEUE="dead_letter_queuea_name";


    //声明延时交换机
    @Bean(DELAY_EXCHANGE)
    public Exchange delayExchange(){
        return ExchangeBuilder.fanoutExchange(DELAY_EXCHANGE).durable(true).build();
    }

    //声明死信交换机
    @Bean(DEAD_LETTER_EXCHANGE)
    public Exchange deadExchange(){
        return ExchangeBuilder.directExchange(DEAD_LETTER_EXCHANGE).durable(true).build();
    }

    //声明延时队列,并绑定死信交换机和死信队列
    @Bean(DELAY_QUEUE)
    public Queue delayQueue(){
        Map map=new HashMap();
        map.put("x-dead-letter-exchange",DEAD_LETTER_EXCHANGE);
        map.put("x-dead-letter-routing-key",DEAD_LETTER_QUEUE);
        //设置此队列延时时间(毫秒)
        map.put("x-message-ttl",1000*60);
        return QueueBuilder.durable(DELAY_QUEUE).withArguments(map).build();
    }

    //声明死信队列
    @Bean(DEAD_LETTER_QUEUE)
    public Queue deadQueue(){
        return new Queue(DEAD_LETTER_QUEUE);
    }

    //延时队列绑定交换机
    @Bean
    public Binding delayQueueABinding(
            @Qualifier(DELAY_QUEUE)Queue queue,
            @Qualifier(DELAY_EXCHANGE)Exchange exchange
    )
    {
        return BindingBuilder.bind(queue).to(exchange).with("").noargs();
    }

    //死信队列绑定交换机
    @Bean
    public Binding deadLetterQueueABinding(
            @Qualifier(DEAD_LETTER_QUEUE)Queue queue,
            @Qualifier(DEAD_LETTER_EXCHANGE)Exchange exchange
    )
    {
        return BindingBuilder.bind(queue).to(exchange).with(DEAD_LETTER_QUEUE).noargs();
    }
}
